<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              所在学校：
              <el-select v-model="selectForm.schoolId" clearable filterable placeholder="请选择">
                <el-option v-for="(school,index) in schoolOption" :key="index" :label="school.schoolName" :value="school.id"></el-option>
              </el-select>
            </div>
            <div>
              事件名称：<el-input placeholder="请输入内容" v-model="selectForm.caseName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              案件性质：
              <el-select v-model="selectForm.caseNature" clearable filterable placeholder="请选择">
                <el-option v-for="(item,index) in caseNatureOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              发生日期：
              <el-date-picker
                v-model="selectForm.happenDate"
                type="date"
                value-format="timestamp"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期时间"
                :picker-options="dataPickerBeforeTodayOptions">
                </el-date-picker>
            </div>
            <div>
              是否破案：
              <el-select v-model="selectForm.hasSolve" clearable placeholder="请选择">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            :before-close="cancel"
            :close-on-click-modal="false"
            class="custom-dialog_style">
            <el-form :model="formData"
                     :rules="rules"
                     :disabled="showOnly"
                     ref="formData">
              <el-form-item label="案(事)件编号：" prop="caseNumber">
                <el-input v-model="formData.caseNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="案(事)件名称：">
                <el-input v-model="formData.caseName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="所在学校：" prop="schoolId">
                <el-select v-model="formData.schoolId" clearable filterable placeholder="请选择">
                  <el-option v-for="(school,index) in schoolOption" :key="index" :label="school.schoolName" :value="school.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发生日期：" prop="happenDate">
                <div class="block">
                  <el-date-picker
                    v-model="formData.happenDate"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期时间"
                    :picker-options="dataPickerBeforeTodayOptions">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="案发地：" prop="happenAddr">
                <el-input v-model="formData.happenAddr" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="案(事)件性质：" prop="caseNature">
                <el-select v-model="formData.caseNature" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in caseNatureOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="抓捕人数：">
                <el-input v-model="formData.capturePersonNum" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="主犯(嫌疑人)证件代码：" prop="pilotIdentityCode">
                <el-select v-model="formData.pilotIdentityCode" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in codeOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="主犯(嫌疑人)证件号码：" prop="pilotIdentityNumber">
                <el-input v-model="formData.pilotIdentityNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="主犯(嫌疑人)姓名：" prop="pilotName">
                <el-input v-model="formData.pilotName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="是否破案：" prop="hasSolve">
                <el-select v-model="formData.hasSolve" clearable placeholder="请选择">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="作案人数：">
                <el-input v-model="formData.casePersonNum" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="在逃人数：">
                <el-input v-model="formData.escapePersonNum" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="案(事)件情况：" prop="caseSituation" class="custom-textarea-container">
                <el-input type="textarea" v-model="formData.caseSituation"></el-input>
              </el-form-item>
              <el-form-item label="案件侦破情况：" prop="caseSolveSituation" class="custom-textarea-container">
                <el-input type="textarea" v-model="formData.caseSolveSituation"></el-input>
              </el-form-item>
              <el-form-item label="所属网格：" prop="gridIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    filterable
                    clearable
                    :props="gridIdProps"
                    v-model="formData.gridIdArr"
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getAllRegion} from '@/utils/region'
import {validateIdefer} from '@/utils/validate'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getStuTeacherSafe, createStuTeacherSafe, updateStuTeacherSafe, delStuTeacherSafe, getSchool} from '@/http/SchoolAroundApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'caseNumber', label: '案（事）件编号' },
        { prop: 'caseName', label: '案（事）件名称' },
        { prop: 'happenDate', label: '发生日期', formatter: this.dateFormatter },
        { prop: 'happenAddr', label: '发生地点' },
        { prop: 'caseNature', label: '案(事)件性质', formatter: this.caseNatureFormatter },
        { prop: 'pilotName', label: '主犯(嫌疑人)姓名' },
        { prop: 'hasSolve', label: '是否破案', formatter: this.hasSolveFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      tableDada: [],
      selectForm: {},
      formData: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      rules: {
        caseNumber: [
          { required: true, message: '请输入案件编号', trigger: 'blur' }
        ],
        happenDate: [
          { required: true, message: '请选择发生日期', trigger: 'blur' }
        ],
        happenAddr: [
          { required: true, message: '请输入案发地', trigger: 'blur' }
        ],
        caseNature: [
          { required: true, message: '请选择案件性质', trigger: 'blur' }
        ],
        pilotIdentityCode: [
          { required: true, message: '请选择证件代码', trigger: 'blur' }
        ],
        pilotIdentityNumber: [
          { validator: validateIdefer, required: true, trigger: 'blur' }
        ],
        pilotName: [
          { required: true, message: '请输入嫌疑人姓名', trigger: 'blur' }
        ],
        hasSolve: [
          { required: true, message: '请选择是否破案', trigger: 'blur' }
        ],
        caseSituation: [
          { required: true, message: '请填写案件情况', trigger: 'blur' }
        ],
        caseSolveSituation: [
          { required: true, message: '请填写案件侦破情况', trigger: 'blur' }
        ],
        schoolId: [
          { required: true, message: '请输入学校ID', trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择所属网格', trigger: 'blur' }
        ]
      },
      schoolOption: [],
      caseNatureOption: [],
      codeOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.getTreeData()
    this.getTableData()
    this.getSchoolData()
    this.caseNatureOption = getDictDataOption('案（事）件性质')
  },
  methods: {
    // 格式化时间戳
    dateFormatter (row, column) {
      let resTime = JSON.parse(row.happenDate)
      return this.$moment(resTime).format('YYYY-MM-DD')
    },
    hasSolveFormatter (row, column) {
      let hasSolve = row.hasSolve === 1 ? '是' : '否'
      return hasSolve
    },
    caseNatureFormatter (row, column) {
      let caseNatureOption = getDictDataOption('案（事）件性质')
      let resCaseNature = ''
      for (let i = 0; i < caseNatureOption.length; i++) {
        if (caseNatureOption[i].code === row.caseNature) {
          resCaseNature = caseNatureOption[i].name
          break
        }
      }
      return resCaseNature
    },
    getSchoolData () {
      let m = this
      getSchool().then(resp => {
        if (resp.code && resp.code === '200') {
          m.schoolOption = resp.data.items
        } else {
          this.$message({
            type: 'info',
            message: '获取学校信息失败'
          })
        }
      })
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.gridIdArr && this.formData.gridIdArr !== 0) {
            let index = this.formData.gridIdArr.length - 1
            let data = {}
            data.id = this.formData.gridIdArr[index]
            data.items = this.treeData
            data.isGetAllId = true
            this.formData.allGridId = getAllRegion(data)
          } else {
            this.formData.allGridId = ''
          }
          if (this.formData.id) {
            updateStuTeacherSafe(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '修改失败'
                })
                return ''
              }
            })
          } else {
            createStuTeacherSafe(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '添加失败'
                })
                return ''
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delStuTeacherSafe(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '删除失败'
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      getStuTeacherSafe(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        this.codeOption = getDictDataOption('证件代码')
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          this.formData = callbackData.rows[0]
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.selectForm.gridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
